package marchsoft.modules.tiku.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.RequiredArgsConstructor;
import marchsoft.enums.ResultEnum;
import marchsoft.exception.BadRequestException;
import marchsoft.modules.system.entity.Dept;
import marchsoft.modules.tiku.entity.ESlideshow;
import marchsoft.modules.tiku.entity.EStudyData;
import marchsoft.modules.tiku.mapper.ESlideshowMapper;
import marchsoft.modules.tiku.mapper.EStudyDataMapper;
import marchsoft.modules.tiku.service.IESlideshowService;
import marchsoft.base.BasicServiceImpl;
import marchsoft.utils.CacheKey;
import marchsoft.utils.FileUtils;
import marchsoft.utils.RedisUtils;
import marchsoft.utils.SecurityUtils;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
import java.security.Key;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
* <p>
* 轮播图 服务实现类
* </p>
*
* @author zsy
* @since 2022-03-29
*/
@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "slideshow")
public class ESlideshowServiceImpl extends BasicServiceImpl<ESlideshowMapper, ESlideshow> implements IESlideshowService {

    private final ESlideshowMapper eSlideshowMapper;
    private final EStudyDataMapper eStudyDataMapper;
    private final RedisUtils redisUtils;
    private final RedisTemplate redisTemplate;

    @Override
    @Cacheable(key = "'all:alls'")
    public List<ESlideshow> getAllSlide() {
        return eSlideshowMapper.selectList(null);
    }

    @Override
    @CacheEvict(key = "'all'" ,allEntries = true)
    public void addSlide(ESlideshow eSlideshow) {
        //如果学习资源id不为空，判断数据库中是否有id资料
        if (ObjectUtil.isNotNull((eSlideshow.getStudyDataId()))) {
            EStudyData eStudyData = eStudyDataMapper.selectById(eSlideshow.getStudyDataId());
            if (ObjectUtil.isNull(eStudyData)) {
                throw new BadRequestException(ResultEnum.STUDY_DATA_NOT_EXIST);
            }
        }
        //学习资料id为空，或者数据库中存在该学习资料
        //判断前端传来的顺序和学习资料id是否与数据库中已有的重复
        LambdaQueryWrapper<ESlideshow> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ESlideshow::getSort, eSlideshow.getSort());
        ESlideshow eSlideshow1 = eSlideshowMapper.selectOne(queryWrapper);
        if (ObjectUtil.isNotNull(eSlideshow1)) {
            throw new BadRequestException(ResultEnum.SLIDE_SHOW_IS_EXIST);
        }
        // 判断存在学习资料id的情况下，学习资料id在轮播图中是否重复
        if (ObjectUtil.isNotNull(eSlideshow.getStudyDataId())) {
            LambdaQueryWrapper<ESlideshow> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ESlideshow::getStudyDataId,eSlideshow.getStudyDataId());
            ESlideshow eSlideshow2 = eSlideshowMapper.selectOne(wrapper);
            if (ObjectUtil.isNotNull(eSlideshow2)) {
                throw new BadRequestException(ResultEnum.SLIDE_SHOW_STUDY_DATA_IS_EXIST);
            }
        }
        //新增轮播图
        int i=eSlideshowMapper.insert(eSlideshow);
        if(i<1){
            throw new BadRequestException(ResultEnum.INSERT_OPERATION_FAIL);
        }
    }


    @Override
    @CacheEvict(key = "'all'",allEntries = true)
    public Integer updateSlide(ESlideshow eSlideshow) {
//        redisUtils.del("404key");

        // 通过id查询当前的轮播图信息
        ESlideshow oldESlideshow = eSlideshowMapper.selectById(eSlideshow.getId());
        // 前端传过来的值studyDataId不为空，；并且和旧值不相同
        if (ObjectUtil.isNotNull(eSlideshow.getStudyDataId()) && !eSlideshow.getStudyDataId().equals(oldESlideshow.getStudyDataId())) {
            EStudyData eStudyData = eStudyDataMapper.selectById(eSlideshow.getStudyDataId());
            if(ObjectUtil.isNull(eStudyData)) {
                throw new BadRequestException(ResultEnum.STUDY_DATA_NOT_EXIST);
            }
            // 判断studyDataId是否重复
            LambdaQueryWrapper<ESlideshow> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ESlideshow::getStudyDataId,eSlideshow.getStudyDataId());
            ESlideshow eSlideshow2 = eSlideshowMapper.selectOne(wrapper);
            if (ObjectUtil.isNotNull(eSlideshow2)) {
                throw new BadRequestException(ResultEnum.SLIDE_SHOW_STUDY_DATA_IS_EXIST);
            }
        }

        if (!oldESlideshow.getSort().equals(eSlideshow.getSort())) {
            LambdaQueryWrapper<ESlideshow> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ESlideshow::getSort,eSlideshow.getSort());
            ESlideshow eSlideshow1 = eSlideshowMapper.selectOne(queryWrapper);
            if (ObjectUtil.isNotNull(eSlideshow1)) {
                throw new BadRequestException(ResultEnum.SLIDE_SHOW_IS_EXIST);
            }
        }

        return eSlideshowMapper.updateSlide(eSlideshow);
    }

    @Override
    @Cacheable(key = "'all:'+#page.current+#p0.size")
    public IPage<ESlideshow> getAll(IPage<Object> page) {
//        redisUtils.set("404key","404value",1, TimeUnit.DAYS);
        IPage<ESlideshow> eSlideshowIPage= eSlideshowMapper.getAllPage(page);
        return eSlideshowIPage;
    }

    @Override
    public void download(List<ESlideshow> eSlideshowList, HttpServletResponse response) {
        if (CollectionUtil.isEmpty(eSlideshowList)) {
            throw new BadRequestException(ResultEnum.FILE_DOWNLOAD_FAIL_NOT_DATA);
        }
        List<Map<String, Object>> list = new ArrayList<>();
        for(ESlideshow eSlideshow:eSlideshowList){
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("轮播图标题",eSlideshow.getTitle());
            map.put("轮播图图片",eSlideshow.getPicPath());
            map.put("学习资料id",eSlideshow.getStudyDataId());
            map.put("资料排序",eSlideshow.getSort());
            list.add(map);
        }
        try {
            FileUtils.downloadExcel(list, response);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    @CacheEvict(key = "'all'",allEntries = true)
    public int deleteByIds(Set<Long> ids) {
        return eSlideshowMapper.deleteEslide(ids);
    }
}

